import React, {useState, useEffect} from 'react';
import {Button, Toast} from 'antd-mobile';
import {CheckUser} from "@/api/role.js" // login api
import {R, ROLE} from "@/assets/js/dict.js"
import './role.scss';

function Role(props) {

    // 去登录
    function handleToLoginPage(role) {
        console.log('props --->>>', props);
        sessionStorage.setItem('roleVal', role)
        // 跳转login
        props.history.push({
            pathname: `/login/${role}`
        })
    }


    function getParam(qs) {
        // eslint-disable-next-line no-unused-expressions
        let search = window.location.href;
        console.log(search);
        var params = search.replace("?", "?&").split("&");
        var rs = "";
        for (var i = 1; i < params.length; i++) {
            if (params[i].indexOf(qs + "=") == 0) {
                rs = params[i].replace(qs + "=", "");
            }
        }
        return rs;
    }

    /*
    * 查询用户是否已经注册，若已经注册直接进行登录
    * */
    function getUserInfo() {
        let code = getParam("code");
        let openid = localStorage.getItem("openid");
        let params = {code: code};
        if (!!openid) {
            params["openid"] = openid;
        }
        CheckUser(params).then(res => {
            if (res.code === "000000") {
                let responseData = res[R.data];
                let wx_openid = responseData['openid'];
                if (wx_openid !== null && wx_openid !== "" && wx_openid !== undefined) {
                    localStorage.setItem("openid", wx_openid);
                } else {
                    console.error("获取openid失败");
                }
                if (responseData && responseData["type"]) {
                    let role = responseData["type"];

                    //直接登录成功，跳转主页
                    if (role === ROLE.P) {
                        sessionStorage.setItem('roleVal', role);
                        sessionStorage.setItem('userInfo', JSON.stringify(responseData));
                        props.history.push({
                            pathname: '/main'
                        });
                    } else if (role === ROLE.T) {
                        sessionStorage.setItem('roleVal', role);
                        sessionStorage.setItem('userInfo', JSON.stringify(responseData));
                        props.history.push({
                            pathname: '/mainTutor'
                        });
                    } else {
                        Toast.fail("未定义的角色[" + role + "]");
                    }
                } else {
                    Toast.offline("检测到您未注册账号，请您注册", 2);
                }
            }
        }).catch((err) => {
            console.log('err ----->>>', err)
        })
    }

    useEffect(() => {
        getUserInfo()
    }, []);

    return (
        <div className="role">
            <div className="role-bg">
                <h1>Hi! 您好！</h1>
                <p>欢迎使用深圳鹏睿家教平台，我们是哈工大（深圳）本校学生创办的正规家教平台，已注册公司，家教老师目前均为哈工大（深圳）在校学生，包括本科生、硕士研究生和博士研究生</p>
            </div>
            <div className="btns">
                <Button type="primary" onClick={() => handleToLoginPage('PARENT')}>我是家长</Button>
                <Button onClick={() => handleToLoginPage('TUTOR')}>我是家教</Button>
            </div>
        </div>
    );
}

export default Role;